package com.example.answer_staff;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.answer_staff.api.ApiManager;
import com.gaosai.staff.domain.MessageResult;
import com.gaosai.staff.domain.User;
import com.gaosai.staff.utils.CommonUtils;
import com.gaosai.staff.utils.JsonUtils;
import com.gaosai.staff.utils.LogUtil;
import com.gaosai.staff.utils.SPUtil;
import com.gaosai.staff.utils.UseCommInterface;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zbar.lib.CaptureActivity;

public class LoginActivity extends Activity {
	private StaffApplication application ;
	private EditText et1;
	private EditText et2;
	private Button bt;
	private ImageView image1;
	private String uniqueId;
	private ImageView info;
	private ImageView logon_problem;
	private ArrayList<String> user_info_list;
	private String username;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
		//隐藏editText弹出的软键盘
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setContentView(R.layout.activity_login);
		setViews();
		uniqueId=CommonUtils.getMyUUID(application);
		setListeners();
	}
	private void setListeners() {
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dengLu();
			}
		});
		image1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				UseCommInterface.getInstance().startActivityForResult(LoginActivity.this, 25, CaptureActivity.class, null) ;
			}
		});
		logon_problem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				jihuo();

			}
			private void jihuo() {
				Intent intent = new Intent(LoginActivity.this,HelpActivity.class);
				startActivity(intent);
			}
		});
		info.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(LoginActivity.this,MainInfomationActivity.class));
				finish();
			}
		});
	}
	protected void dengLu() {
		username = et1.getText().toString();
		Log.i("111", "username"+username);
		final String passwordold = et2.getText().toString();
		Log.e("eee", "LoginActivity界面的passwordold是"+passwordold);
		Log.e("eee", "LoginActivity界面的SPUTIL.password是"+SPUtil.getValue(application, SPUtil.PASSWORD));

		String password =CommonUtils. Md5(passwordold);
		Log.i("111", "开始连接服务器");
		if(username.length()<3||password.length()<6){
			Toast.makeText(getApplicationContext(), "用户名不能少于三位，密码不能小于六位",1).show();
			return;
		}
		/**登陆*/
		ApiManager.getInstance().login(LoginActivity.this, username, password, uniqueId, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
			}

			@Override
			public void onFinish() {
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
			}
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				//登陆成功以后就将密码存入sharedPreference里边；

				String result = new String(arg2) ;
				LogUtil.e("login result", result) ;
				MessageResult messageResult = MessageResult.prase(result);
				if(0==messageResult.getCode()){
					//登陆成功之后，将username保存起来。
					SPUtil.putValue(getApplicationContext(), SPUtil.USERNAME, username);
					//					LogUtil.e("data:", messageResult.getData()) ;
					JSONObject jsonObject;
					try {
						jsonObject = new JSONObject(messageResult.getData());
						User user = User.parse(jsonObject.opt("user").toString()) ;
						if(null !=user){
							application.setUser(user) ;
							//登陆的成功的时候将userid放到shaerdprefence里边，需要的时候，再将其取出来就可以了。
							SPUtil.putValue(LoginActivity.this, SPUtil.USERID, user.getUserId()) ;
							LogUtil.e("user:", user.toString()) ;
							Toast.makeText(LoginActivity.this, messageResult.getMsg(), 0).show() ;
							Intent intent= new Intent(LoginActivity.this,NewsRoomActivity.class);
							//							intent.putExtra("user_info_list", user_info_list);
							Log.e("eee", "返回的是user_info_list是"+user_info_list);
							startActivity(intent);
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
						System.out.println("登陆出异常了");
					}
				}else{
					Toast.makeText(LoginActivity.this, messageResult.getMsg(), 0).show() ;
				}
			}
		}) ;
	}
	private void setViews() {
		application = (StaffApplication) getApplication() ;
		et1 = (EditText) findViewById(R.id.et1);
		et2 = (EditText) findViewById(R.id.et2);
		bt = (Button) findViewById(R.id.bt1);
		image1=(ImageView)findViewById(R.id.imageView1);
		logon_problem=(ImageView)findViewById(R.id.logon_problem);
		info=(ImageView)findViewById(R.id.info);
	}
	//跳转到激活界面向服务器传值。
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			String barCode;
			switch (requestCode) {
			case 25:
				barCode = data.getStringExtra("result") ;
				Log.i("eee", "zhixing偏好设置了");
				Log.i("eee", "barcode是否为空"+barCode.isEmpty());
				//				Toast.makeText(LoginActivity.this, "结果是："+barCode, 0).show() ;
				//				ApiManager.getInstance().activeQRCode(LoginActivity.this, barCode,uniqueId, new AsyncHttpResponseHandler()
				ApiManager.getInstance().changeDeviceQRCode(LoginActivity.this, barCode,uniqueId, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
					}
					@Override
					public void onFinish() {
						super.onFinish();
					}
					@Override
					public void onStart() {
						super.onStart();
					}
					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						String result = new String(arg2) ;
						MessageResult messageResult = MessageResult.prase(result);
						Log.e("eee", "二维码 result是"+result);
						if(0==messageResult.getCode()){
							Log.e("eee", "二维码 messageResult.getData()是"+messageResult.getData());
							//得到服务器返回的userinfo里边的内容。服务器返回的数据是已经解码过的数据
							user_info_list=JsonUtils.JsonResultUserInfo(messageResult.getData().toString());
							String[] barcode_string = JsonUtils.ParseQr(user_info_list.toString());
							//							SPUtil.putValue(LoginActivity.this, SPUtil.BARCODE+barcode_string[1], user_info_list.toString());
							//存入sd卡里边
							CommonUtils.saveToSd(LoginActivity.this,  SPUtil.BARCODE+barcode_string[1], user_info_list.toString());
							Log.e("eee", "二维码 user_info_list是"+user_info_list);
							Log.e("eee", "二维码 barcode+userName是"+SPUtil.BARCODE+barcode_string[1]);
							Intent intent=new Intent(LoginActivity.this,ActivaActivity.class);
							intent.putExtra("user_info_list", user_info_list);
							startActivity(intent);
						}else{
							Toast.makeText(LoginActivity.this, messageResult.getMsg(), 0).show() ;
						}
					}
				}) ;

				break;

			}
		}
	}
}
